package online.hxstart.code.concurrent.chapter04;

/**
 * @author huxing
 * @date 19-4-24 星期三 上午11:47
 * @describe
 */
public class DeadLock {

  private final Object MUTEX_READ = new Object();
  private final Object MUTEX_WRITE = new Object();

  private void read() {
    synchronized (MUTEX_READ) {
      System.out.println(Thread.currentThread().getName() + " get READ lock");
      synchronized (MUTEX_WRITE) {
        System.out.println(Thread.currentThread().getName() + " get WRITE lock");
      }
      System.out.println(Thread.currentThread().getName() + " release READ lock");
    }
  }

  public void write() {
    synchronized (MUTEX_WRITE) {
      System.out.println(Thread.currentThread().getName() + " get WRITE lock");
      synchronized (MUTEX_READ) {
        System.out.println(Thread.currentThread().getName() + " get READ lock");
      }
      System.out.println(Thread.currentThread().getName() + " release WRITE lock");
    }
  }

  public static void main(String[] args) {

    final DeadLock deadLock = new DeadLock();
    new Thread(
            () -> {
              while (true) {
                deadLock.read();
              }
            },
            "Thread-READ")
        .start();
    new Thread(
            () -> {
              while (true) {
                deadLock.write();
              }
            },
            "Thread-WRITE")
        .start();
  }
}
